<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/27 21:01
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

use Wechat\Loader;

class Login extends WX_Controller
{
    /**
     * 初始化
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 静默登录
     *
     * @url http://wx.api.qiuqiugu.com/baseLogin?code=011V7V600EFIsC1t6S400RW5700V7V67&state=
     */
    public function index()
    {
        $token = Loader::get('oauth');
        $return = $token->getOauthAccessToken();
        if (empty($return)) {
            echo $token->errMsg;
            exit;
        }

        $openId = value($return, 'openid');
        $authState = value($_GET, 'state');
        $redirect_uri = $this->routes['map'][$authState];

        if (empty($redirect_uri)) {
            $redirect_uri = 'index';
        }

        // 检查用户是否跟本地用户有关联
        $this->load->model('wx/user/Social_Model', 'social');
        $userid = 0;
        $userType = 0;
        if ($userInfo = $this->social->checkUserRegist($openId)) {
            $userid = $userInfo['userid'];
            $user = $this->social->getUserById($userid);
            $userType = value($user, 'userType');
            $this->social->updateLoginTime($openId);
        } else {
            // 保存用户信息
            $user = $this->_getUserInfo($openId);
            if ($user) {
                $this->social->saveUserInfo($user);
                $userid = $this->social->getSaveUserId();
                $userType = 0;
            }
        }

        if (empty($userid)) {
            show_404();
            exit;
        }

        $this->session->set_userdata('openId', $openId);
        $this->session->set_userdata('userid', $userid);
        $this->session->set_userdata('userType', $userType);
        redirect($redirect_uri);
        exit;
    }

    /**
     * 从微信获取用户资料
     * @param $openId
     * @return array|bool
     */
    private function _getUserInfo($openId)
    {
        $user = Loader::get('user');
        return $user->getUserInfo($openId);
    }

}
